package com.easychat.controller;

import com.easychat.annotation.GlobalInterceptor;
import com.easychat.common.Result;
import com.easychat.entity.AppUpdate;
import com.easychat.entity.AppUpdateVO;
import com.easychat.entity.config.AppConfig;
import com.easychat.entity.constants.Constants;
import com.easychat.enums.AppUpdateFileTypeEnum;
import com.easychat.service.AppUpdateService;
import com.easychat.utils.StringTools;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;

/**
 * (AppUpdate)表控制层
 *检测更新
 * @author makejava
 * @since 2024-10-14 16:39:29
 */
@RestController("updateController")
@RequestMapping("update")
public class UpdateController {
    /**
     * 服务对象
     */
    @Resource
    private AppUpdateService appUpdateService;
    @Resource
    private AppConfig appConfig;

    /**
     * 检测版本更新
     * @param appVersion
     * @return
     */
    @GetMapping("/checkVersion")
    @GlobalInterceptor(checkAdmin = true)
    public Result<AppUpdateVO> checkVersion(String appVersion,String uid){
        if(StringTools.isEmpty(appVersion)){
            return Result.ok();
        }
        AppUpdate appUpdate = appUpdateService.getLatestUpdate(appVersion,uid);
        if(appUpdate == null){
            return Result.ok();
        }
        AppUpdateVO appUpdateVO = new AppUpdateVO();
        BeanUtils.copyProperties(appUpdate,appUpdateVO);
        if(AppUpdateFileTypeEnum.LOCAL.getType().equals(appUpdate.getFileType())){
            File file = new File(appConfig.getProjectFolder() + Constants.APP_UPDATE_FOLDER + appUpdate.getId() + Constants.APP_EXE_SUFFIX);
            appUpdateVO.setSize(file.length());
        }else {
            appUpdateVO.setSize(0L);
        }

        appUpdateVO.setUpdateList(Arrays.asList(appUpdate.getUpdateDescArray()));
        String fileName = Constants.APP_NAME + appUpdate.getVersion() + Constants.APP_EXE_SUFFIX;

        return Result.ok(appUpdateVO);
    }




}

